package com.rlz.framemm.util;

import com.rlz.libs.log.P;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;


import static com.rlz.framemm.util.SoFile.UP_SO_ZIP_PATH;

/**
 * Created by RLZ
 * on 2021/4/26
 * <p>
 * 简单的解压缩文件  不推荐使用  推荐使用XZ或者7z格式
 */
public class ZipHelper {
    private static final int BUFFER_SIZE = 1024 * 1024;

    /**
     * 解压缩一个文件
     */
    public static int upZip(File zipFile) throws IOException {
        File desDir = new File(UP_SO_ZIP_PATH);
        if (!desDir.exists()) {
            desDir.mkdirs();
        } else {
            File[] files = desDir.listFiles();
            assert files != null;
            if (files.length > 0) {
                P.d("已经解压过了 跳过");
                return files.length;
            }
        }
        ZipFile zf = new ZipFile(zipFile);
        for (Enumeration<?> entries = zf.entries(); entries.hasMoreElements(); ) {
            ZipEntry entry = (ZipEntry) entries.nextElement();
            if (entry.isDirectory()) {
                continue;
            }

            InputStream is = zf.getInputStream(entry);
            String str = UP_SO_ZIP_PATH + File.separator + entry.getName();
            str = new String(str.getBytes("8859_1"), StandardCharsets.UTF_8);
            File desFile = new File(str);
            if (!desFile.exists()) {
                File fileParentDir = desFile.getParentFile();
                if (!fileParentDir.exists()) {
                    fileParentDir.mkdirs();
                }
                desFile.createNewFile();
            }
            OutputStream os = new FileOutputStream(desFile);
            byte[] buffer = new byte[BUFFER_SIZE];
            int length;
            while ((length = is.read(buffer)) > 0) {
                os.write(buffer, 0, length);
            }
            os.flush();
            os.close();
            is.close();
        }
        return 0;
    }
}
